#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    sock = new QTcpSocket(this);
    connect(sock, SIGNAL(connected()),
            this, SLOT(on_connected()));
    connect(sock, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(on_error()));
    connect(sock, SIGNAL(disconnected()),
            this, SLOT(on_disconnected()));
    connect(sock, SIGNAL(readyRead()),
            this, SLOT(on_readyRead()));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_clicked()
{
    if (ui->pushButton->text() == "Connect")
    {
        sock->connectToHost(ui->lineEdit->text(), ui->spinBox->value());
    }

    if (ui->pushButton->text() == "Disconnect")
    {
        sock->disconnectFromHost();
    }
}

void Widget::on_connected()
{
    QString msg = "%1 is connected";
    ui->plainTextEdit->appendPlainText(msg.arg(ui->lineEdit->text()));
    ui->pushButton->setText("Disconnect");
}

void Widget::on_error()
{
    ui->plainTextEdit->appendPlainText(sock->errorString());
}

void Widget::on_disconnected()
{
    QString msg = "%1 is disconnected";
    ui->plainTextEdit->appendPlainText(msg.arg(ui->lineEdit->text()));
    ui->pushButton->setText("Connect");
}

void Widget::on_readyRead()
{
    QString msg = "> " + QString(sock->readAll());
    ui->plainTextEdit->appendPlainText(msg);
}

void Widget::on_sendButton_clicked()
{
    QString msg = ui->msgEdit->text() + "\r\n";
    ui->plainTextEdit->appendPlainText("< " + ui->msgEdit->text());
    sock->write(msg.toLocal8Bit());
}
